#include "io_context_pool.h"
#include <sys/poll.h>


AsioContextPool::AsioContextPool(std::size_t size)
:_io_contexts(size)
,_works(size)
,_threads(size)
,_thread_size(size)
,_next(0)
{
    for(std::size_t i = 0; i < size; ++i)
    {
        _works[i] = WrokPtr(new Work(_io_contexts[i]));
        _threads.emplace_back([this, i](){
            _io_contexts[i].run();
        });
    }
}

AsioContextPool::~AsioContextPool()
{
    stop();
}

AsioContextPool::IOContext& AsioContextPool::get_io_context()
{
    _next %= _thread_size;
    return _io_contexts[_next++];
}


void AsioContextPool::stop()
{
    for(auto& work: _works)
    {
        work.reset();
    }

    for(auto& thread: _threads)
    {
        thread.join();
    }
}